package com.zhku.shoppingspringboot.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhku.shoppingspringboot.common.R;
import com.zhku.shoppingspringboot.common.ResultCode;
import com.zhku.shoppingspringboot.common.myPageInfo;
import com.zhku.shoppingspringboot.pojo.dto.SearchDTO;
import com.zhku.shoppingspringboot.pojo.entity.Brand;
import com.zhku.shoppingspringboot.pojo.entity.Categories;
import com.zhku.shoppingspringboot.pojo.entity.Goods;
import com.zhku.shoppingspringboot.pojo.vo.GoodsStockVO;
import com.zhku.shoppingspringboot.pojo.vo.GoodsVO;
import com.zhku.shoppingspringboot.pojo.vo.SearchVO;
import com.zhku.shoppingspringboot.pojo.vo.hotGoodsVO;
import com.zhku.shoppingspringboot.service.ICategoriesService;
import com.zhku.shoppingspringboot.service.IGoodsService;
import com.zhku.shoppingspringboot.utils.FileUtils;
import io.swagger.annotations.ApiOperation;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.Id;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.zhku.shoppingspringboot.service.impl.GoodsServiceImpl.convertStringToList;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jieeee
 * @since 2025-01-02
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ICategoriesService categoriesService;
    @Autowired
    private SessionFactory sessionFactory; // 注入 SessionFactory

    private final String imgUrl = "D:\\shopping\\Goods\\";
    //    //文件保存正在服务器的文件夹
    private final String uploadDir = "D:\\shopping\\Goods\\";


    @GetMapping("/stock/{id}")
    public R<GoodsStockVO> getGoodsStock(@PathVariable Long id){
        Goods byId = goodsService.getById(id);
        GoodsStockVO goodsStock = BeanUtil.copyProperties(byId, GoodsStockVO.class);
        goodsStock.setNowPrice(byId.getPrice()).setEffective(true).setStock(byId.getInventory());
        return R.success(goodsStock);
    }
    @Transactional
    @GetMapping()
    public R<com.zhku.shoppingspringboot.pojo.entity.goodsData.Goods> getGoodsInfo(@RequestParam Long id){
        com.zhku.shoppingspringboot.pojo.entity.goodsData.Goods oneGoods = goodsService.getOneGoods(id);
        return R.success(oneGoods);
    }

    @PostMapping("/search")
    @Transactional
    public R<SearchVO> searchGoods(@RequestBody SearchDTO searchDTO){
        PageHelper.startPage(searchDTO.getPage(), searchDTO.getPageSize());
        List<GoodsVO> goodsVOS= goodsService.searchAll(searchDTO.getKeyword());
       PageInfo<GoodsVO> PageInfo = new PageInfo<>(goodsVOS);
        myPageInfo<GoodsVO> searchVOPageInfo = myPageInfo.conversion(PageInfo);
//        使用herbeinate获取brands
        Session session = sessionFactory.getCurrentSession(); // 获取当前会话
        String hql = "FROM Brand ";
        Query<Brand> query = session.createQuery(hql, Brand.class);
        List<Brand> results = query.list();

        SearchVO searchVO = new SearchVO().setPageData(searchVOPageInfo).setBrand(results);
        return R.success(searchVO);
    }
//猜你喜欢
    @GetMapping("/newGoods")
    public R<List<GoodsVO>> newGoods(){
//        随机获取数据
        QueryWrapper<Goods> queryWrapper=new QueryWrapper<Goods>()
                .orderByDesc("RAND()");
        List<Goods> list = goodsService.list(queryWrapper).stream().limit(4).collect(Collectors.toList());
        List<GoodsVO> collect = list.stream().map(item -> new GoodsVO().setId(String.valueOf(item.getId()))
                .setName(item.getName())
                .setDesc(item.getDesc())
                .setPrice(String.valueOf(item.getPrice()))
                .setPicture(item.getMainPictures().replace("[", "").replace("]", "").split(",")[0])
                .setDiscount(Math.round(item.getDiscount()))
                .setOrderNum(item.getSalesCount())).collect(Collectors.toList());
        return R.success(collect);
    }
    @GetMapping("/allGoods")
    public R<List<GoodsVO>> allGoods(){
        List<Goods> list = goodsService.list();
        List<GoodsVO> collect = list.stream().map(item -> new GoodsVO().setId(String.valueOf(item.getId()))
                .setName(item.getName())
                .setDesc(item.getDesc())
                .setPrice(String.valueOf(item.getPrice()))
                .setPicture(item.getMainPictures().replace("[", "").replace("]", "").split(",")[0])
                .setDiscount(Math.round(item.getDiscount()))
                .setOrderNum(item.getSalesCount())).collect(Collectors.toList());
        return R.success(collect);
    }
    @PostMapping("/uploadimg")
    public R<String> uploadProfilePicture( @RequestBody MultipartFile file) {
        String oldPath="";
        String result = FileUtils.upLoadImg(uploadDir, oldPath, file);
        if (result.equals("-1")) {
            return R.error(ResultCode.VALIDATE_FAILED, "请检查文件类型");
        } else if (result.equals("-2")) {
            return R.error(ResultCode.ERROR, "服务器出错啦");
        }
        return R.success("操作成功",imgUrl + result);
    }

  @PostMapping("/addGoods")
  @CacheEvict(value = "shopping",key ="'categories_*'")
    public R<String> addGoods(@RequestBody Goods goods){
      boolean save = goodsService.save(goods);
      if (save){
          return R.success("添加成功");
      }else {
          return R.error(ResultCode.ERROR);
      }
  }
    @PutMapping("/updateGoods")
    @CacheEvict(value = "shopping",key ="'categories_*'")
    public  R<String> updateGoods(@RequestBody Goods goods){
        boolean update = goodsService.updateById(goods);
        if (update){
            return R.success("更改成功");
        }else {
            return R.error(ResultCode.ERROR);
        }
    }

    @DeleteMapping("/deleteGoods")
    public  R<String> deleteGoods(@RequestParam Long id){

        boolean remove = goodsService.removeById(id);
        if (remove){
            return R.success("删除成功");
        }else {
            return R.error(ResultCode.ERROR);
        }
    }
@GetMapping("/inventoryWarning")
    public R<List<Goods>> inventoryWarning(){
    List<Categories> categories = categoriesService.list();
    LambdaQueryWrapper<Goods> lambdaQueryWrapper=new LambdaQueryWrapper<Goods>()
                .le(Goods::getInventory,20).select(Goods::getId,Goods::getName,Goods::getCategories,Goods::getInventory);
    List<Goods> list = goodsService.list(lambdaQueryWrapper);
    List<Goods> resultList=new ArrayList<>();
    for (Goods goods : list) {
//        获得商品的id
        String categoriesIdString = goods.getCategories();
        List<String> categoriesIds = convertStringToList(categoriesIdString);
//        转换成id
        List<Integer> ids = categoriesIds.stream().map(Integer::parseInt)
                .collect(Collectors.toList());
        String categoriesName = categories.stream()
                .filter(category -> ids.contains(category.getId()))
                .map(Categories::getName)
                .collect(Collectors.joining(", "));
        goods.setCategories(categoriesName);
        resultList.add(goods);
    }
    return R.success(resultList);
}

}

